// 引入包名
import http from '@ohos.net.http';
import router from '@ohos.router';

let token: string = AppStorage.Get("token")

class MyResponse implements http.HttpResponse {
  performanceTiming: http.PerformanceTiming;

  cookies: string;
  header: Object;
  responseCode: number | http.ResponseCode;
  resultType: http.HttpDataType;
  result: {
    code: number
    msg: string
    data: Object
  };
}

class MyRequest implements http.HttpRequestOptions {
  method: http.RequestMethod
  header: Object
  readTimeout: number
  connectTimeout: number
  extraData: string | Object | ArrayBuffer

  constructor() {
  }
}

// 工厂模式获取request对象
function getMyRequest(): MyRequest {
  let myRequest: MyRequest = new MyRequest()
  let myHeader = {
    'Content-Type': 'application/json;charset=utf-8',
    'Authorization': token
  }
  myRequest.header = myHeader
  return myRequest
}

// 请求前设置
function beforeRequest(url: string, data: Object | string, method: http.RequestMethod): Promise<http.HttpResponse> {
  token = AppStorage.Get("token")
  let baseURL: string = 'http://wuzhuya.top:8081/api';
  if (url == "" || url.length == 0) {
    // MessageUtil("请求失败", "url不能为空")
    return Promise.reject(new Error("url不能为空"))
  }

  if (url != "/login" && url != "/register") {
    if (token == "" || token == undefined || token.length == 0) {
      // MessageUtil("请求失败", "登录失败")
      // 跳转到登录页面
      router.pushUrl({ url: 'pages/login' })
      return Promise.reject(new Error("登录失效"))
    }
  }
  url = baseURL + url
  let myRequest: MyRequest = getMyRequest()
  myRequest.method = method
  myRequest.extraData = data
  let httpRequest: http.HttpRequest = http.createHttp()
  return httpRequest.request(url, myRequest)
}

async function afterRequest(requestData: MyRequestData): Promise<Object> {
  try {
    let myPromise: Promise<Object>;
    await beforeRequest(requestData.url, requestData.data, requestData.method).then((res: http.HttpResponse) => {
      if (res.responseCode != 200) {
        throw new Error("请求失败")
      }
      let myData = JSON.parse(res.result.toString())
      if (myData.code != 0) {
        if (myData.code == 6000 || myData.code == 7000 || myData.code == 8000) {
          router.pushUrl({ url: "pages/login" })
          throw new Error(myData.msg)
        }
        throw new Error(myData.msg)
      }
      myPromise = new Promise<Object>((resolve, reject) => {
        resolve(myData.data)
      })
    })
    return myPromise
  } catch (error) {
    // return Promise.reject(error)
    return new Promise<Object>((resolve, reject) => {
      reject("test")
    })
  }
}

export default function request(myRequestData: MyRequestData): Promise<Object> {
  return afterRequest(myRequestData)
}

class MyRequestData {
  url: string;
  method: http.RequestMethod;
  data: Object | string

  constructor(url: string, method: http.RequestMethod, data: Object | string) {
    this.url = url;
    this.method = method;
    this.data = data;
  }
}